package com.vstudy.zx.service.impl;

import com.vstudy.zx.dao.ConversationDao;
import com.vstudy.zx.dao.MessageDao;
import com.vstudy.zx.entity.Conversation;
import com.vstudy.zx.entity.Message;
import com.vstudy.zx.service.ConversationService;
import com.vstudy.zx.utils.page.ConversationPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class ConversationServiceImpl implements ConversationService {
    @Autowired
    private ConversationDao conversationDao;
    @Autowired
    private MessageDao messageDao;

    @Override
    @Transactional(readOnly = true)
    public int count(Long te_id, Boolean status) {
        return conversationDao.count(te_id, status);
    }

    @Override
    public List<Conversation> getConversations(ConversationPage page) {
        int count = conversationDao.count(page.getTe_id(), page.getStatus());
        page.setTotalCount((long) count);
        if (page.getPageIndex() > page.getPageCount()) {
            page.setPageIndex(page.getPageCount());
        }
        if (page.getPageIndex() < 1) {
            page.setPageIndex(1L);
        }
        List<Conversation> conversations = conversationDao.selectByPage(page);
        for (Conversation c :
                conversations) {
            Message message = messageDao.selectLastMessage(c.getCon_id());
            c.setLastMsg(message);
        }
        return conversations;
    }

    @Override
    public Boolean signRead(List<Long> arr) {
        String sql_in = "";
        for (Long a :
                arr) {
            sql_in += a + ",";
        }
        sql_in = sql_in.substring(0, sql_in.length() - 1);
        int i = conversationDao.signRead(sql_in);
        if (i == arr.size()) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean removeConvs(List<Long> ids) {
        String sql_in = "";
        for (Long a :
                ids) {
            sql_in += a + ",";
        }
        sql_in = sql_in.substring(0, sql_in.length() - 1);
        int i = conversationDao.removeConvs(sql_in);
        if (i == ids.size()) {
            return true;
        }
        return false;
    }

    @Override
    public Long getConId(Long stuId, Long te_id) {
        Conversation c1 = conversationDao.selectByStuTe(stuId, te_id);
        if (c1 == null) {
            Conversation conversation = new Conversation();
            conversation.setStu_id(stuId);
            conversation.setTe_id(te_id);
            conversation.setCon_status(true);
            conversationDao.add(conversation);
            return conversation.getCon_id();
        } else {
            return c1.getCon_id();
        }
    }

}
